﻿using TbShop.Business.Components;
using TbShop.Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace TbShop.Web.Helpers
{
    /// <summary>
    /// 全局缓存
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class CacheHelper<T> where T : DataEntityBase
    {
        public static T GetById(int id)
        {
            return GetAll().FirstOrDefault(p => p.Id == id);
        }

        private static Dictionary<Type, object> Datas = new Dictionary<Type, object>();

        public static IEnumerable<T> GetAll()
        {
            var key = GetKey();
            if (!Datas.Keys.Any(p => p == key) || Datas[key] == null)
            {
                ServiceComponents<T> bc = new ServiceComponents<T>();
                var items = Datas[key] = bc.GetAll().ToList();
                if (!Datas.Keys.Any(p => p == key))
                {
                    Datas.Add(key, items);
                }
                else
                {
                    Datas[key] = items;
                }
            }
            return Datas[key] as IEnumerable<T>;
        }

        public static void ClearDates()
        {
            var key = GetKey();
            if (Datas.Keys.Any(p => p == key))
            {
                Datas[key] = null;
            }
        }

        private static Type GetKey()
        {
            return typeof(T);
        }
    }

    public class CacheSelectItemHelper<T> : CacheHelper<T> where T : SelectItemEntityBase
    {
        public static IEnumerable<SelectListItem> GetSelectList()
        {
            var SetMealSource = from c in GetAll()
                                select new { Key = c.Id.ToString(), Value = c.Name };
            return DropdownHelper.ConvertToSelectListItem(SetMealSource);
        }
    }
}